package com.example.spider.util;

import javax.net.ssl.*;
import java.net.Socket;
import java.net.URLConnection;
import java.security.cert.X509Certificate;

public class SkipHttpsVerifyUtil {

    public static void trustAllCerts(URLConnection urlConnection) {
        if (!(urlConnection instanceof HttpsURLConnection)) {
            return;
        }
        SSLContext ctx = SkipHttpsVerifyUtil.createTrustAllSSLContext();
        ((HttpsURLConnection) urlConnection).setSSLSocketFactory(ctx.getSocketFactory());
        ((HttpsURLConnection) urlConnection).setHostnameVerifier((hostname, sslSession) -> true);
    }

    public static SSLContext createTrustAllSSLContext() {
        TrustManager[] tm = {new SkipVerifyX509TrustManager()};
        SSLContext ctx = null;
        try {
            ctx = SSLContext.getInstance("TLS");
            ctx.init(null, tm, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ctx;
    }

    /**
     * HTTPS忽略证书验证,防止高版本jdk因证书算法不符合约束条件,使用继承X509ExtendedTrustManager的方式
     */
    public static class SkipVerifyX509TrustManager extends X509ExtendedTrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) {

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1, Socket arg2) {
        }

        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1, SSLEngine arg2) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1, Socket arg2) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1, SSLEngine arg2) {
        }
    }
}


